package cn.bailin233.system.service.Impl;

import cn.bailin233.system.entity.user.User;
import cn.bailin233.system.mapper.UserMapper;
import cn.bailin233.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户表服务实现类
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 通过账号密码登录获取uid
    public Long doLogin(String name, String pwd) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("account", name)
                .eq("password", pwd);
        User user = userMapper.selectOne(wrapper);
        if (user == null) return null;
        return user.getUid();
    }

    // 获取用户角色
    @Override
    public List<String> getRoleNameList(Long uid) {
        return userMapper.getRoleNameList(uid);
    }

    // 获取用户资源(权限)
    @Override
    public List<String> getResourceNameList(Long uid) {
        return userMapper.getResourceNameList(uid);
    }

    // 存储第三方accessToken
    @Override
    public void insertAccessToken(Long uid, String accessToken) {
        redisTemplate.boundValueOps("satoken:login:accessToken:"+uid).set(accessToken);
    }

    // 读取第三方accessToken
    @Override
    public String findAccessToken(Long uid) {
        return redisTemplate.boundValueOps("satoken:login:accessToken:"+uid).get();
    }

    // 注册
    @Override
    public int insertOne(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("account", user.getAccount());
        if (userMapper.selectOne(wrapper) != null) return -1;
        if (userMapper.insert(user) != 1) return 0;
        else return 1;
    }

    // 通过第三方账号获取uid
    @Override
    public Long loginInOauthName(String oauthName) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("oauth_name", oauthName);
        User user = userMapper.selectOne(wrapper);
        if (user == null) return null;
        return user.getUid();
    }

    // 账号绑定
    @Override
    public int binDing(Long uid, String oauthName) {
        User user = userMapper.findByUid(uid);
        if (user != null) {
            user.setOauthName(oauthName);
            UpdateWrapper<User> wrapper = new UpdateWrapper<>();
            wrapper.set("oauth_name", oauthName).isNull("oauth_name").eq("uid", user.getUid());
            int i = userMapper.update(user, wrapper);
            if (i == 1) return 1;
            else return -1;
        } else {
            return 0;
        }

    }
}
